package io.renren.modules.substation.service.impl;

import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.substation.dao.TSampThDataInfoHisDao;
import io.renren.modules.substation.entity.TSampThDataInfoHisEntity;
import io.renren.modules.substation.service.TSampThDataInfoHisService;

import javax.annotation.Resource;


@Service("tSampThDataInfoHisService")
public class TSampThDataInfoHisServiceImpl extends ServiceImpl<TSampThDataInfoHisDao, TSampThDataInfoHisEntity> implements TSampThDataInfoHisService {
	@Resource
	private TSampThDataInfoHisDao tSampThDataInfoHisDao;
	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<TSampThDataInfoHisEntity> page = this.page(
				new Query<TSampThDataInfoHisEntity>().getPage(params),
				new QueryWrapper<TSampThDataInfoHisEntity>()
		);

		return new PageUtils(page);
	}

	/**
	 * 获取环境温湿度图表
	 *
	 * @return 环境温湿度图表
	 *         temperatureAxis: 温度轴
	 *         humidityAxis: 湿度轴
	 */
	@Override
	public Map<String, List<?>> chartEnvironment() {
		// 获取24小时的历史数据
		List<TSampThDataInfoHisEntity> list = tSampThDataInfoHisDao.get24Data();

		// 结果数据
		Map<Long, Map<String, Float>> resultMap = new LinkedHashMap<>();

		// 获取24小时前的时间
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		long oneHourMillis = 1000L * 60 * 60;
		while (calendar.getTimeInMillis() < System.currentTimeMillis() - oneHourMillis) {
			// 获取起始时间和结束时间
			long startMillis = calendar.getTimeInMillis();
			calendar.add(Calendar.HOUR_OF_DAY, 1);
			long endMillis = calendar.getTimeInMillis();

			// 获取该时间段的平均值
			float temperature = 0;
			float humidity = 0;

			// 该时间段的数量（用于求平均值）
			int temperatureCount = 0;
			int humidityCount = 0;
			for (TSampThDataInfoHisEntity sampThDataInfoHisEntity : list) {
				if (sampThDataInfoHisEntity.getCreateTime() == null) {
					continue;
				}

				// 如果在当前小时
				long createTime = sampThDataInfoHisEntity.getCreateTime().getTime();
				if (createTime > startMillis && createTime <= endMillis) {
					if (sampThDataInfoHisEntity.getAmbientTemp() != null) {
						temperature += Float.parseFloat(sampThDataInfoHisEntity.getAmbientTemp());
						temperatureCount++;
					}
					if (sampThDataInfoHisEntity.getRelativeHumidity() != null) {
						humidity += Float.parseFloat(sampThDataInfoHisEntity.getRelativeHumidity());
						humidityCount++;
					}
				}
			}

			// 计算平均值
			temperature = temperatureCount == 0 ? temperature : temperature / temperatureCount;
			humidity = humidityCount == 0 ? humidity : humidity / humidityCount;
			// 精确1为小数
			DecimalFormat decimalFormat = new DecimalFormat("#.#");
			temperature = Float.parseFloat(decimalFormat.format(temperature));
			humidity = Float.parseFloat(decimalFormat.format(humidity));

			// 封装当前小时的数据
			Map<String, Float> hourMap = new HashMap<>(2);
			hourMap.put("temperature", temperature);
			hourMap.put("humidity", humidity);
			resultMap.put(endMillis, hourMap);
		}


		// 封装数据
		return new HashMap<String, List<?>>(2) {{
			// x轴
			List<String> xAxis = new LinkedList<>();
			// y轴
			List<Float> temperatureAxis = new LinkedList<>();
			List<Float> humidityAxis = new LinkedList<>();

			// 取数据
			resultMap.forEach((millis, hourMap) -> {
				DateFormat dateFormat = new SimpleDateFormat("d日H时");
				xAxis.add(dateFormat.format(new Date(millis)));
				temperatureAxis.add(hourMap.get("temperature"));
				humidityAxis.add(hourMap.get("humidity"));
			});

			put("xAxis", xAxis);
			put("temperatureAxis", temperatureAxis);
			put("humidityAxis", humidityAxis);
		}};
	}

}